package com.ibm.cloud.banking.prod.service;


import com.ibm.cloud.banking.platform.exception.BusinessException;
import com.ibm.cloud.banking.prod.constant.TransErrorMgt;
import com.ibm.cloud.banking.prod.convert.ProductInfoMapper;
import com.ibm.cloud.banking.prod.dto.*;
import com.ibm.cloud.banking.prod.entity.ProductCondition;
import com.ibm.cloud.banking.prod.entity.ProductInfoEntity;
import com.ibm.cloud.banking.prod.repository.ProductConditionMapper;
import com.ibm.cloud.banking.prod.repository.ProductInfoRepository;
import com.sun.istack.NotNull;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import javax.annotation.Resource;


@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = RuntimeException.class)
public class ProductParameterQueryServiceImpl implements IProductParameterQueryService {

    final static String PRODUCT_STATUS_NORMAL = "1";
    @Resource
    private ProductInfoRepository productInfoRepository;

    @Autowired
    private IVendibiCmptQueryComponent vendibiCmptQueryComponentImpl;

    @Resource
    private ProductInfoMapper productInfoMapper;

    @Resource
    private ProductConditionMapper productConditionMapper;

    @Override
    public ProductInfo checkProductAvailable(ProductCheckDTO productDTO) {
        return this.checkProductAvailable(productDTO.getProductNo(),productDTO.getTransDate());
    }

    @Override
    public ProductInfo checkProductAvailable(@NotNull String productNo, Date transDate) {
        if (transDate == null) {
            throw new BusinessException(TransErrorMgt.PARAM_VALUE_IS_NULL.code,
                    String.format(TransErrorMgt.PARAM_VALUE_IS_NULL.message, "交易日期"));
        }

//        ProductInfoExample example = new ProductInfoExample();
//        ProductInfoExample.Criteria criteria = example.createCriteria();
//        criteria.andProductNoEqualTo(productNo);
        Optional<ProductInfoEntity> optionalProductInfoEntity = productInfoRepository.findByProductNo(productNo);
        if (optionalProductInfoEntity.isEmpty()) {
            throw new BusinessException("PROD-001","产品不存在");
        }

        ProductInfo productInfo = productInfoMapper.entityToDto(optionalProductInfoEntity.get());

        //检查产品状态
        if (PRODUCT_STATUS_NORMAL.equals(productInfo.getStatus())==false) {
            throw new BusinessException(TransErrorMgt.PRODUCT_NOT_ALLOW_SALES.code,
                    TransErrorMgt.PRODUCT_NOT_ALLOW_SALES.message);
        }

        //检查产品可售日期
        Calendar transDt = Calendar.getInstance();
        transDt.setTime(transDate);

        Calendar startDt = Calendar.getInstance();
        startDt.setTime(productInfo.getStartDate());

        Calendar endDt = Calendar.getInstance();
        endDt.setTime(productInfo.getEndDate());

        // 检查产品是否在允许销售日期范围内
        if (transDt.after(endDt) || transDt.before(startDt)) {
            throw new BusinessException(TransErrorMgt.PRODUCT_NOT_ALLOW_SALES.code,
                    TransErrorMgt.PRODUCT_NOT_ALLOW_SALES.message);
        }

        return productInfo;
    }

    public void checkAcctProduct(ProductCheckDTO productDto){
        // 开户 1
        if(productDto.getType()==1)
            this.checkOpenAcctProduct(productDto.getProductNo(),new BigDecimal(productDto.getAmount()),productDto.getAccountCategory());
       //转败
        else if(productDto.getType()==2)
            this.checkTransformProduct(productDto.getProductNo(),new BigDecimal(productDto.getAmount()),productDto.getAccountCategory());

        // this.checkAcctProduct(productDto.getProductNo(),new BigDecimal(productDto.getAmount()),productDto.getAccountCategory());
    }

    public void checkTransformProduct(String productNo, BigDecimal transAmount, String accountCategory) {
        List<ProductCondition> conditions = productConditionMapper.selectByPrimaryProdNo(productNo);
        Optional.ofNullable(conditions).ifPresent(conds -> {
            conds.forEach(item -> {
                if(item.getProdtCondNo().equals("CPCS0000000527")) {
                    if(1==item.getProdtCondMinVal().compareTo(transAmount)) {
                        throw new BusinessException(TransErrorMgt.PRODUCT_TRANS_MIN_VAL_OUT.code,
                                TransErrorMgt.PRODUCT_TRANS_MIN_VAL_OUT.message);
                    }
                }
                if(item.getProdtCondNo().equals("CPCS0000000528")) {
                    if(-1==item.getProdtCondMaxVal().compareTo(transAmount)) {
                        throw new BusinessException(TransErrorMgt.PRODUCT_TRANS_MAX_VAL_OUT.code,
                                TransErrorMgt.PRODUCT_TRANS_MAX_VAL_OUT.message);
                    }
                }
            });
        });
    }


    public void checkOpenAcctProduct(String productNo, BigDecimal transAmount, String accountCategory) {
        List<ProductCondition> conditions = productConditionMapper.selectByPrimaryProdNo(productNo);
        Optional.ofNullable(conditions).ifPresent(conds -> {
            conds.forEach(item -> {
                if(item.getProdtCondNo().equals("CPCS0000000526")) {
                    if(-1==item.getProdtCondMaxVal().compareTo(transAmount)) {
                        throw new BusinessException(TransErrorMgt.PRODUCT_MAX_VAL_OUT.code,
                                TransErrorMgt.PRODUCT_MAX_VAL_OUT.message);
                    }
                }
                if(item.getProdtCondNo().equals("CPCS0000000519")) {
                    if(1==item.getProdtCondMinVal().compareTo(transAmount)) {
                        throw new BusinessException(TransErrorMgt.PRODUCT_MIN_VAL_OUT.code,
                                TransErrorMgt.PRODUCT_MIN_VAL_OUT.message);
                    }
                }
            });
        });
    }

    public void checkAcctProduct(String productNo, BigDecimal transAmount, String accountCategory) {
        VendibiProdtCmptInfoIn in = new VendibiProdtCmptInfoIn();
//		in.setVendibiProdtNo(productNo);
        in.setProdtCmptNo("ZJXD00000273");
//		in.setVendibiProdtNo("zjxdoooooo273");
        in.setVendibiProdtNo("P20101060001");
        in.setVendibiProdtVerNo("v1");
        VendibiProdtCmptInfoOut out = vendibiCmptQueryComponentImpl.doNoTxProdtCmptInfo(in);
        List<VendibiProdSimpleConditionInfo> condInfoList = out.getProdCondInfoList();
        Boolean AccFlagY = false;
        for(VendibiProdSimpleConditionInfo tmp:condInfoList) {
            if(tmp.getProdtCondNo().equals("CPCS0000000526")) {
                if(tmp.getUpLmtPackIncluFlag().equals("1")) {
                    if(-1==tmp.getProdtCondMaxVal().compareTo(transAmount)) {
                        throw new BusinessException(TransErrorMgt.PRODUCT_MAX_VAL_OUT.code,
                                TransErrorMgt.PRODUCT_MAX_VAL_OUT.message);
                    }
                }
            }
            if(tmp.getProdtCondNo().equals("CPCS0000000519")) {
                if(tmp.getLowLmtPackIncluFlag().equals("1")) {
                    if(1==tmp.getProdtCondMinVal().compareTo(transAmount)) {
                        throw new BusinessException(TransErrorMgt.PRODUCT_MIN_VAL_OUT.code,
                                TransErrorMgt.PRODUCT_MIN_VAL_OUT.message);
                    }
                }
            }
//			if(accountCategory.equals("1")) {
//				if(tmp.getProdtCondNo().equals("CPCS0000000507")) {
//						AccFlagY = true;
//				}
//			}
//			if(accountCategory.equals("2")) {
//				if(tmp.getProdtCondNo().equals("CPCS0000000508")) {
//						AccFlagY = true;
//				}
//			}
            if(accountCategory.equals("1")) {
                if(tmp.getProdtCondNo().equals("CPCS0000000642")) {
                    AccFlagY = true;
                }
            }
            if(accountCategory.equals("2")) {
                if(tmp.getProdtCondNo().equals("CPCS0000000642")) {
                    AccFlagY = true;
                }
            }

        }
        //TODO 逻辑是啥？
//        if (!AccFlagY) {
//            throw new BusinessException(TransErrorMgt.PRODUCT_ACC_NOT_MATCH.code,
//                    TransErrorMgt.PRODUCT_ACC_NOT_MATCH.message);
//        }

    }

    public void checkProductTmp(String str) {

    }
}
